/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.ipleiria.plp.threads;

import java.util.Enumeration;
import java.util.Vector;
import pt.ipleiria.plp.BlackSpotterMidlet;
import pt.ipleiria.plp.Lixeiras.LixeiraSent;

/**
 *
 * @author filipe
 */
public class GetLixeirasPendentes extends Thread {

    BlackSpotterMidlet midlet;
    CallbackReturnPendentes screen;

    public GetLixeirasPendentes(BlackSpotterMidlet midlet, CallbackReturnPendentes screen) {
        this.midlet = midlet;
        this.screen = screen;
    }

    public void run() {
        LixeiraSent[] lixs = LixeiraSent.getAllPending(midlet.getApp().getAppKey());
        Vector vecRet = new Vector();
        StringBuilder strLixEditadas = new StringBuilder();

        if (lixs == null) {
            screen.returnPendentes(null, null);
        }
        System.out.println("Number recieved from server: " + lixs.length);
        boolean algumEdited = false;
        for (int i = 0; i < lixs.length; i++) {
            if (midlet.getApp().getManager().searchLixeirasPorEnviadar(lixs[i].getGuid()) != null) {
                algumEdited = true;
                strLixEditadas.append(lixs[i].getTitle() + "\n");
            } else {
                midlet.getApp().getManager().appendOrUpdateLixeirasEnviadas(lixs[i]);
                vecRet.addElement(lixs[i]);
            }
        }
        if (!algumEdited) {
            screen.returnPendentes(lixs, null);
        } else {

            LixeiraSent[] lixRet = new LixeiraSent[vecRet.size()];
            Enumeration enume = vecRet.elements();
            int i = 0;
            while (enume.hasMoreElements()) {
                lixRet[i] = (LixeiraSent) enume.nextElement();
                i++;
            }
            System.out.println("Number being returned: " + lixRet.length);
            screen.returnPendentes(lixRet, strLixEditadas.toString());
        }
    }
}
